package com.anpy.security.security;

import org.springframework.security.access.expression.SecurityExpressionRoot;
import org.springframework.security.access.expression.method.MethodSecurityExpressionOperations;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;

/**
 * Custom security expression root for platform-specific authorization checks.
 * This allows for expressions like:
 * - hasPlatformRole('ADMIN')
 * - hasPlatformPermission('READ_USER')
 */
public class PlatformSecurityExpressionRoot extends SecurityExpressionRoot implements MethodSecurityExpressionOperations {

    private Object filterObject;
    private Object returnObject;

    public PlatformSecurityExpressionRoot(Authentication authentication) {
        super(authentication);
    }

    /**
     * Check if the current user has a specific role in the current platform context
     * 
     * @param role The role name without platform prefix
     * @return true if the user has the role in the current platform
     */
    public boolean hasPlatformRole(String role) {
        String platformCode = PlatformContextHolder.getPlatformCode();
        if (platformCode == null) {
            return false;
        }
        
        String fullRoleName = "ROLE_" + platformCode + "_" + role;
        
        return getAuthentication().getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(authority -> authority.equals(fullRoleName));
    }
    
    /**
     * Check if the current user has a specific permission in the current platform context
     * 
     * @param permission The permission name without platform prefix
     * @return true if the user has the permission in the current platform
     */
    public boolean hasPlatformPermission(String permission) {
        String platformCode = PlatformContextHolder.getPlatformCode();
        if (platformCode == null) {
            return false;
        }
        
        String fullPermissionName = platformCode + "_" + permission;
        
        return getAuthentication().getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(authority -> authority.equals(fullPermissionName));
    }

    @Override
    public Object getFilterObject() {
        return this.filterObject;
    }

    @Override
    public Object getReturnObject() {
        return this.returnObject;
    }

    @Override
    public Object getThis() {
        return this;
    }

    @Override
    public void setFilterObject(Object obj) {
        this.filterObject = obj;
    }

    @Override
    public void setReturnObject(Object obj) {
        this.returnObject = obj;
    }
}
